<?php
class Cms_Models_Node extends Ext_Db_Table
{
	protected $_name = 'cms_node';

    public function getContentFromTid( $tid )
    {
        if( empty( $tid )){
            return array();
        }
        
        $rowset = $this->getAdapter()->fetchAll(
            $this->getAdapter()->select()
            ->from( array( 'tn' => 'cms_node_taxonomy' ) )
            ->join( array( 'no' => $this->_name ), 'no.node_id = tn.node_id', array( '*' ) )
            ->where( "tn.taxonomy_id = ?", $tid )
            ->where( "no.published = '1' " )
            ->where( "no.locked = 'F' " )
        );
        return $rowset;
    }
    
	public function load( $nid )
	{
		$fNode = new Cms_Models_NodeFile();
		$row = $this->find( $nid )->current();
		$node['hdr'] = ( count( $row ) ? $row->toArray() : array() );
		$node['files'] = $fNode->getFiles( $nid );
		return $node;
	}
	
	public function getAll( $where )
	{
		return $this->fetchAll( "locked = 'F'")->toArray();
	}
	
	
	public function getQueryList()
	{
		$query = $this->getAdapter()->select()
			->from( array( 'no' => $this->_name ), array('*')  )
			->join( 
				array( 'ty' => 'cms_content_type'), 
				'ty.content_type_id = no.content_type_id', 
				array('type' => 'ty.title') 
			);
		return $query;
	}
	
	public function save( $params )
	{
		if( empty ( $params['node_id'])){
			$row = $this->createRow();
		} else {
			$row = $this->fetchRow(
				$this->select()
				->where('node_id = ?', $params['node_id'])
			);
			if( ! count( $row )) {
				$row = $this->createRow();
			}
		}
		$row->setFromArray( $params );
		return (int)$row->save();
		
	}
	
	public function getNodesPageFront( $type )
	{
		if( empty( $type )){
			return array();
		}
		$query = $this->select()
			->where( 'locked = ?', 'F'  )
			->where( 'content_type_id = ?', $type )
			->where( 'published = ?', 'T')
			->where( 'page_front = ?', 'T' );
			
		$rowset = $this->fetchAll( $query );
		if( count( $rowset ) ) {
			return $rowset->toArray();
		}
		return array();
	}
}